<script setup>
import api from '../api/admin_api.js'  // 管理员接口路径
import { ref, onMounted } from "vue";
import { ElMessageBox } from "element-plus";
import lodash from 'lodash'

// 数据定义区域
const tableData = ref([]);
const total = ref(0);
const editWinVisible = ref(false);

// 默认头像URL
const defaultAvatar = 'https://easy-travel.oss-cn-beijing.aliyuncs.com/ef48330c-5dd9-4035-98e1-9e0c0e2cf5f0.png';

const searchObj = ref({
  current: 1,
  limit: 10,
  adminname: '',
  email: ''
});

const obj = ref({});
const handleUploadSuccess = (response,file) => {

  obj.value.photo=response.data;
};
// 查询方法
const search = async () => {
  const result = await api.page(searchObj.value);
  tableData.value = result.data;
  total.value = result.count;
};

onMounted(async () => {
  await search();
});

const editCancel = () => {
  obj.value = {};
  editWinVisible.value = false;
};

const editCommit = async () => {
  if (obj.value.id) {
    await api.edit(obj.value);
  } else {
    await api.add(obj.value);
  }
  search();
  editWinVisible.value = false;
};

const handleSearch = () => {
  searchObj.value.current = 1;
  search();
};

const handleSizeChange = (val) => {
  searchObj.value.limit = val;
  search();
};

const handleCurrentChange = (val) => {
  searchObj.value.current = val;
  search();
};
// 当前登录用户信息
const loginUser = ref({
  role: localStorage.getItem("role") || "admin", // 默认为admin，实际应该从登录信息中获取
  id: localStorage.getItem("userId") || null
});
const handleAdd = () => {
  obj.value = {
    adminname: '',
    password: '',
    photo: '',
    email: ''
  };
  editWinVisible.value = true;
};

const handleEdit = (index, row) => {
  obj.value = lodash.clone(row);
  editWinVisible.value = true;
};
const handleCleanupImages = async () => {
  try{
    await api.cleanupImages();
    ElMessageBox.confirm('清理成功')
  }catch(error){
    coonsole.error(error);
    ElMessageBox.error('清理失败')
  }
}
const handleDelete = (index, row) => {
  ElMessageBox.confirm(
      '确认删除该管理员吗？',
      '删除提示',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'error'
      }
  )
      .then(async () => {
        await api.del(row.id);
        searchObj.value.current = 1;
        search();
      })
      .catch(() => {});
};
const isAdminLogin = () => {
  return loginUser.value.role === 'admin';
}

// 处理头像加载错误
const handleAvatarError = (event) => {
  event.target.src = defaultAvatar;
};
</script>

<template>
  <div class="admin-management-container">
    <!-- 查询表单 -->
    <el-form :inline="true" :model="searchObj" style="margin-top: 10px; margin-bottom: 15px;">
      <el-form-item label="管理员账号">
        <el-input v-model="searchObj.adminname" placeholder="请输入管理员账号" clearable style="width: 200px;" />
      </el-form-item>
      <el-form-item label="邮箱">
        <el-input v-model="searchObj.email" placeholder="请输入邮箱" clearable style="width: 200px;" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleAdd">新增</el-button>
      </el-form-item>
      <el-form-item v-if="isAdminLogin()">
        <el-button type="danger" @click="handleCleanupImages">清理无用图片</el-button>
      </el-form-item>
    </el-form>

    <!-- 管理员列表 -->
    <el-table
        :data="tableData"
        style="width: 100%; margin-bottom: 20px;"
        border
        stripe
        :header-cell-style="{ 'background-color': '#f5f7fa', 'font-weight': 'bold' }">
      <!--    >-->
      <!--      <el-table-column label="ID" width="80" align="center">-->
      <!--        <template #default="scope">-->
      <!--          {{ scope.row.id }}-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <el-table-column label="管理员账号" min-width="150">
        <template #default="scope">
          {{ scope.row.adminname }}
        </template>
      </el-table-column>
      <el-table-column label="邮箱" min-width="200">
        <template #default="scope">
          {{ scope.row.email }}
        </template>
      </el-table-column>
      <!-- 头像列（支持点击预览） -->
      <el-table-column label="头像" min-width="200">
        <template #default="scope">
          <el-image
              :src="scope.row.photo ? scope.row.photo : defaultAvatar"
              class="img-avatar"
              :preview-src-list="[scope.row.photo ? scope.row.photo : defaultAvatar]"
              fit="cover"
              @error="handleAvatarError"
          />
        </template>
      </el-table-column>

      <el-table-column label="操作" min-width="180" align="center">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
              style="margin-left: 5px;"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        v-model:current-page="searchObj.current"
        v-model:page-size="searchObj.limit"
        :page-sizes="[10, 20, 30, 50]"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        style="text-align: right; margin-top: 10px;"
    />

    <!-- 编辑/新增对话框 -->
    <el-dialog v-model="editWinVisible" title="编辑管理员信息" width="500px">
      <el-form :model="obj" label-width="100px">
        <el-form-item label="ID" v-if="obj.id">
          <el-input v-model="obj.id" disabled />
        </el-form-item>
        <el-form-item label="管理员账号" required>
          <el-input v-model="obj.adminname" autocomplete="off" />
        </el-form-item>
        <el-form-item label="密码" required>
          <el-input v-model="obj.password" type="password" autocomplete="off" />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="obj.email" autocomplete="off" />
        </el-form-item>
        <el-form-item label="头像":label-width="100">
          <el-upload
              class="avatar-uploader"
              action="/api/upload/file"
              :show-file-list="false"
              :on-success="handleUploadSuccess"

          >
            <img :src="obj.photo ? obj.photo : defaultAvatar" @error="handleAvatarError" class="avatar-preview" />

          </el-upload>

        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editCancel">取消</el-button>
          <el-button type="primary" @click="editCommit">提交</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<style scoped>
.img-avatar {
  width: 100px;
  height: 100px;
  border-radius: 4px;  /* 圆角效果 */
  cursor: pointer;  /* 鼠标悬停显示手型，提示可点击 */
}

.avatar-preview {
  width: 100px;
  height: 100px;
  object-fit: cover;
  border-radius: 6px;
}

</style>
